// ==UserScript==
// @name         速卖通评论分析脚本
// @namespace    pacey
// @version      0.1
// @description  get aliexpress feedback
// @author       pacey
// @updateURL    https://gitee.com/great-pacey/tampermonkey/raw/master/comment.analysis.user.js
// @match        *://feedback.aliexpress.com/display/productEvaluation.*
// @require      https://code.jquery.com/jquery-3.6.0.min.js
// @connect writewords.org.uk
// @grant GM_setValue
// @grant GM_getValue
// @grant GM_deleteValue
// @grant unsafeWindow
// @grant window.close
// @grant window.focus
// @grant GM_setClipboard
// @grant GM_xmlhttpRequest
// @connect gitee.com
// ==/UserScript==
let productId;
new Image().src = 'https://unpkg.com/element-ui/lib/theme-chalk/index.css';
new Image().src = 'https://unpkg.com/vue/dist/vue.js';
new Image().src = 'https://unpkg.com/element-ui/lib/index.js';
new Image().src = 'https://cdn.jsdelivr.net/npm/echarts@5.1.2/dist/echarts.min.js';

(function () {
  'use strict';
  $(function () {
    unsafeWindow.document.title = '评论页面';
    let feedbackList = [];
    let form = $('#l-refresh-form')[0];

    function getPage(page) {
      return new Promise((resolve, reject) => {
        let formdata = new FormData(form);
        formdata.set('page', page);
        formdata.set('currentPage', page > 1 ? page - 1 : '');

        let data = [...formdata.entries()].reduce((o, [k, v]) => (o[k] = v, o), {});
        
        if (!productId) {
          productId = data.productId;
        }

        data.evaSortValue = "sortlarest@feedback";
        data.translate = 'N';

        $.ajax({
          type: form.method,
          url: form.action,
          data: data,
          success: resolve,
          error: reject
        });
      });
    }

    function parseFeedback(html) {
      return html.find('.feedback-item').map(function () {
        let feedback = {};
        let item = $(this);
        let userName = item.find('.fb-user-info .user-name a');
        feedback.userName = userName.text().trim();
        feedback.memberDetailUrl = userName.attr('href');

        let userCountry = item.find('.fb-user-info .user-country');
        feedback.userCountry = userCountry.text().trim();

        let star = item.find('.fb-main .star-view span');
        let starMatch = star.attr('style').match(/width:\s*?(\d+?)%/);
        if (starMatch) {
          feedback.star = Math.round(starMatch[1] / 20);
        }

        let orders = item.find('.fb-main .user-order-info > span');
        orders.each(function () {
          let order = $(this);
          let strs = order.text().trim().replace(/物流/, 'Logistics:').split(':');
          // if (strs.length !== 2) {
          //   strs = order.text().trim().match(/^(.+?)\s(.+)/);
          //   strs.shift();
          // }
          feedback[strs[0].trim().replace(/\s/ig, '_').toLowerCase()] = (strs[1] || '').trim();
        });

        let buyer = item.find('.fb-main .buyer-feedback');
        let timeNew = buyer.find('.r-time-new');
        feedback.timeNew = timeNew.text().trim();
        feedback.feedback = buyer.text().replace(timeNew.text(), '').trim();

        let photos = item.find('.fb-main .pic-view-item img');
        feedback.photos = photos.map(function () {
          return $(this).attr('src');
        }).get();
        return feedback;
      }).get();
    }

    function getPageStr(page) {
      return page == 0 ? '' : '：' + page;
    }
    
    let loading = false;
    function loop(page, list) {
      loading = true;
      page = page || 1;
      return getPage(page).then((val) => {
        let html = $(val.replace(/<!DOCTYPE\s.*?>/ig, '').replace(/<(\/?)(html|body|head)>/ig, '<$1div>'));
        list = (list || []).concat(parseFeedback(html));

        let paginationNext = html.find('#complex-pager .ui-pagination-next');
        if (paginationNext.length > 0) {
          loadAll.text(`已爬取${getPageStr(list.length)}条`);
        }
        if (--MAX_COUNT > 0 && paginationNext.length > 0 && !paginationNext.hasClass('ui-pagination-disabled')) {
          return loop(page + 1, list);
        } else {
          loading = false;
          return list;
        }
      })
    }

    let openNewTab = $('<button style="margin-left: 20px;">去分析</button>').on('click', function () {
      window.open(location.href);
    });

    let MAX_COUNT = 500;
    function _loadAll() {
      console.log(document.body.querySelector('#maxCountInput').value);
      MAX_COUNT = Math.min(Number((document.body.querySelector('#maxCountInput').value) || MAX_COUNT, MAX_COUNT));
      return loop().then(function (list) {
        feedbackList = list;
        log();
      });
    }

    function log() {
      if (feedbackList.length > 0) {
        unsafeWindow.m = feedbackList;
        console.log('feedbackList', feedbackList);
      }
    }

    let loadAll = $(`<button style="margin-left: 10px;">开始爬取${getPageStr(feedbackList.length)}</button>`).on('click', () => {
      if (loading) return;
      unsafeWindow.document.title = '爬取中...';
      _loadAll().then(() => {
        unsafeWindow.document.title = '爬取完成';
        $('.customer-reviews').append([goDetailPageButton]);
        goDetailPage();
        loadAll.text('重新爬取');
      })
    });

    function runScript(script, win){
      return new Promise((reslove, rejected) => {
        const newScript = win.document.createElement('script');
        newScript.innerHTML = script.innerHTML;
        const src = script.getAttribute('src');
        if (src) newScript.setAttribute('src', src);
        
        newScript.onload = () => reslove();
        newScript.onerror = err => rejected();
        win.document.head.appendChild(newScript);
        win.document.head.removeChild(newScript);
        if (!src) {
          reslove();
        }
      })
    }

    function setHTMLWithScript(win, rawHTML){
      const container = win.document.documentElement;
      container.innerHTML = rawHTML;
      const scripts = container.querySelectorAll('script');

      return Array.prototype.slice.apply(scripts).reduce((chain, script) => {
        return chain.then(() => runScript(script, win));
      }, Promise.resolve());
    }

    function goDetailPage() {
      const url = 'https://gitee.com/great-pacey/tampermonkey/raw/master/comment.analysis.code.js';
      let newWin = window.open();
      newWin.data = feedbackList;
      newWin.productId = productId;
      newWin.document.title = '评论分析';
      GM_xmlhttpRequest({
        method:"GET",
        url,
        headers:  {
          "Content-Type":"application/x-www-form-urlencoded"
        },
        onload: function(res)
        {
          let html = res.responseText;
          setHTMLWithScript(newWin, html);
        }
      });
    }

    const maxCountInput = $('<label style="margin-left: 20px;">输入你想加载多少页（一页10条）：<input id="maxCountInput" style="margin-right:20px; width: 150px;" placeholder="最多500页"></label>');

    const goDetailPageButton = $("<button style='margin-left:30px;'>打开分析界面</button>").on('click', goDetailPage);

    if (top === window) {
      $('.customer-reviews').append([maxCountInput, loadAll]);
    } else {
      $('.customer-reviews').append([openNewTab]);
    }

    log();
  });
})();